<?php
namespace Home\Controller;
use Think\Controller;
use Think\Verify;
class IndexController extends Controller {
    /**
     * 首页面
     */
    public function index(){
        if(!empty($_SESSION['loginUser_Index'])){
            $this->redirect('showIndex');
        } else {
            // 检查cookie
            $loginUser = cookie('yida_login_user');
            if(isset($loginUser) && !empty($loginUser)){
                $this->excuteLogin($loginUser);
                $this->redirect('showIndex');
            } else {
                $contentModel = D('Content');
                $maxId = $contentModel->max('id');
                $where['id'] = $maxId;
                $content = $contentModel->where($where)->getField('detail');
                $this->assign('content', $content);
                $this->display('cover');
            }
        }
    }
    
    /**
     * 显示模板页
     */
    public function showIndex(){
        // 设定入口城市
        $entryCityModel = new \Home\Model\EntryCityModel();
        $entryCityId = I('get.id', "", 'htmlspecialchars');
        $rlt = $entryCityModel->relation(true)->order("id asc")->select();
        if(empty($entryCityId)){
            $_SESSION['current_city_id'] = $rlt[0]['city_id']; // 设定当前城市默认为第一个入口城市
            $this->assign("current_city", $rlt[0]['city_name']);
        } else {
            $where['id'] = $entryCityId;
            $entryCity = $entryCityModel->where($where)->relation(true)->select();
            $_SESSION['current_city_id'] = $entryCity[0]['city_id'];
            $this->assign("current_city", $entryCity[0]['city_name']);
        }
        
        $entry_cities = array();
        $index = 0;
        $item = array();
        $columnLen = 6;
        foreach ($rlt as $entryCity){
            if($index == $columnLen){
                $entry_cities[] = $item;
                $item = array();
                $index = 0;
            }
            $item[$index] = $entryCity;
            $index++;
        }
        if(count($item) < $columnLen){
            $entry_cities[] = $item;
        }
        $this->assign("entry_cities", $entry_cities);
        
        // 检查是否已经登录
        if(!empty($_SESSION['loginUser_Index'])){
            // 已经登录
            $user_id = $_SESSION['loginUser_Index'];
            $userModel = D("User");
            $where['id'] = $user_id;
            $rlt = $userModel->where($where)->select();
            if(!empty($rlt[0]['real_name'])){
                $name_show = $rlt[0]['real_name'];
            } else if(!empty($rlt[0]['username']) && $rlt[0]['username'] != $rlt[0]['phone']){
                $name_show = $rlt[0]['username'];
            } else{
                $name_show = $rlt[0]['user_code'];
            }
            $this->assign("display_name", $name_show);
        }
        
        $currentYear = date('Y');
        $this->assign('currentYear', $currentYear);
        $this->display('index');
    }
    
    /**
     * 显示登录页面
     */
    public function showLogin(){
        if(!empty($_SESSION['loginUser_Index'])){
            $this->redirect("showIndex");
            exit;
        }
        $this->display('login');
    }
    
    /**
     * 显示注册页面
     */
    public function showRegister(){
        if(!empty($_SESSION['loginUser_Index'])){
            $this->redirect("showIndex");
            exit;
        }
        $this->display('register');
    }
    
    /**
     * 检查是否已有用户登录
     */
    public function checkHasLogined(){
        if(!empty($_SESSION['loginUser_Index'])){
            echo "true";
        } else {
            echo "false";
        }
    }
    
    /**
     * 注册
     */
    public function register(){
    	// 账号信息(手机号)
    	$username = I('post.username', '', 'htmlspecialchars');
    	// 密码
    	$password = I('post.password', '', 'htmlspecialchars');
        $userModel = D("User");
        $where['phone'] = $username;
        $rlt = $userModel->where($where)->select();
        if(isset($rlt)){
        	echo json_encode(array("status"=>300,"name"=>"","user_id"=>0, "message"=>"该手机号已经被注册"));  // 该手机号已经被注册
        } else {
        	$data['username'] = $username;
        	$data['password'] = md5($password);
        	$data['real_name'] = "";
        	$data['phone'] = $username;
        	$data['register_time'] = date('Y-m-d');
        	$data['vip_level'] = 0;
        	$data['safe_level'] = 0;
        	$user_code = $this->getUsercode();
        	$data['user_code'] = $user_code;
        	$rlt = $userModel-> data($data)->add();
        	if($rlt != false && $rlt > 0){
        	    // 登录成功时记录登录信息
        	    if($this->addLoginRecord($rlt) == true){
        	        $this-> excuteLogin($rlt);
        	        echo json_encode(array("status"=>200,"name"=>$user_code,"user_id"=>$rlt, "message"=>"注册成功")); 
        	    } else {
        	        echo json_encode(array("status"=>200,"name"=>$user_code,"user_id"=>$rlt, "message"=>"注册成功,但未能成功登录"));
        	    }
        	} else {
        		echo json_encode(array("status"=>201,"name"=>"","user_id"=>0, "message"=>"注册失败")); 
        	}
        }
    }
    
    /**
     * 获取唯一的用户编号
     * @return Ambigous <string, number>
     */
    private function getUsercode(){
        $userModel = D("User");
        $user_code_max = $userModel->getField("max(user_code)");
        $user_code = intval($user_code_max) + 1;
        $user_code = sprintf("%08d",$user_code);
        return $user_code;
    }
    
    /**
     * 登录
     */
    public function login(){
        // 账号信息(手机号)
    	$username = I('post.username', '', 'htmlspecialchars');
    	// 密码
    	$password = I('post.password', '', 'htmlspecialchars');
    	// 7天自动登录
    	$checkIn = I('post.checkin', '', 'htmlspecialchars');
    	$userModel = D("User");
    	$where['username'] = $username;
    	$where['phone'] = $username;
    	$where['user_code'] = $username;
    	$where["_logic"]="OR";
    	$rlt = $userModel->where($where)->select();
    	if(isset($rlt)){
    	    if(md5($password) != $rlt[0]['password']){
    	        echo json_encode(array("code"=>201,"name"=>"","user_id"=>"","message"=>"密码不成确"));  // 密码不正确
    	    } else {
    	        if(!empty($rlt[0]['real_name'])){
    	            $name_show = $rlt[0]['real_name'];
    	        } else if(!empty($rlt[0]['username']) && $rlt[0]['username'] != $rlt[0]['phone']){
    	            $name_show = $rlt[0]['username'];
    	        } else{
    	            $name_show = $rlt[0]['user_code'];
    	        }
    	        // 登录成功时记录登录信息
    	        if($this->addLoginRecord($rlt[0]['id']) == true){
    	            $this-> excuteLogin($rlt[0]['id']);
    	            // 在cookie中记录登录信息
    	            if(intval($checkIn) == 1){
    	                cookie('login_user',$username,array('expire'=>3600 * 24 * 7,'prefix'=>'yida_'));
    	            }
    	            echo json_encode(array("code"=>200,"name"=>$name_show,"user_id"=>$rlt[0]['id'],"message"=>"登录成功")); // 登录成功
    	        } else {
    	            echo json_encode(array("code"=>201,"name"=>"","user_id"=>"","message"=>"登录失败"));  // 密码不正确
    	        }
    	    }
    	} else {
    	    echo json_encode(array("code"=>400,"name"=>"","user_id"=>"","message"=>"用户不存在"));  // 用户不存在
    	}
    }
    
    /**
     * 记录登录信息
     * @param  $user_id 登录或新注册的用户id
     * @return boolean
     */
    private function addLoginRecord($user_id){
        // 获取本次登录的位置信息
        $Ip = new \Org\Net\IpLocation('UTFWry.dat'); // 实例化类 参数表示IP地址库文件
        $area = $Ip->getlocation(); // 获取某个IP地址所在的位置
        $ipAddress = $area['ip'];
        $country = $area['country'];
        $location = $area['area'];
        $data['ip'] = $ipAddress;
        $data['login_time'] = date("Y-m-d H:i:s");
        $data['login_location'] = $country;
        // 获取上次登录的位置信息
        $where['user_id'] = $user_id;
        $loginRecordModel = D('LoginRecord');
        $rlt = $loginRecordModel->order("login_time desc")->limit("0,1")->select();
        if(!empty($rlt) && count($rlt) > 0){
            $data['prev_ip'] = $rlt[0]['ip'];
            $data['prev_login_time'] = $rlt[0]['login_time'];
            $data['prev_login_location'] = $rlt[0]['login_location'];
        }
        $rs = $loginRecordModel->data($data)->add();
        if($rs > 0){
            return true;
        } else {
            return false;
        }
    }
    
    /**
     * 执行登录处理
     */
    private function excuteLogin($user_id){
        // 将用户名存放到session中
        $_SESSION['loginUser_Index'] = $user_id;
    }
    
    /**
     * 退出
     */
    public function logout(){
        // 将session中的用户名清除
        $_SESSION['loginUser_Index'] = null;
        $_SESSION['current_city_id'] = null;
        cookie('yida_login_user',null);
        echo "success";
    }
    
    /**
     * 进入主页面
     */
    public function main(){
        // === 入口城市 ===
        // 入口城市MODEL
        $entryCityModel = new \Home\Model\EntryCityModel();
        $entryCityList = $entryCityModel->relation(true)->select();
        $this->assign("entryCityList", $entryCityList);
    
        $locationCityId = $_SESSION['current_city_id'];
        if(!isset($locationCityId) || empty($locationCityId)){
            $locationCityId = $entryCityList[0]['city_id'];
        }
    
        // === 广告 ===
        // 广告model
        $advertisementModel = D("Advertisement");
        $rlt = $advertisementModel->order("update_time desc")->limit("0".','."4")->select();
        $this->assign("advertisementList", $rlt);
    
        // === 景点 ===
        // 景点model
        $attractionModel = D('Attraction');
        unset($where);
        $where['city_id'] = $locationCityId;
        $where['is_recommend'] = 1;
        $rlt = $attractionModel->where($where)->limit("0".','."4")->select();
        if(empty($rlt)){
            $rlt = $attractionModel->order("update_time desc")->limit("0".','."4")->select();
        }
        $this->assign("attractionList", $rlt);
    
        // === 周边游 ===
        // 周边游model
        $aroundModel = D('Around');
        unset($where);
        $where['orign'] = $locationCityId;
        $where['is_recommend'] = 1;
        $rlt = $aroundModel->where($where)->limit("0".','."2")->select();
        if(empty($rlt)){
            $rlt = $aroundModel->order("update_time desc")->limit("0".','."2")->select();
        }
        $this->assign("aroundList", $rlt);
    
        //=== 旅游攻略 ===
        // 旅游攻略model
        $travelTipModel = D('TravelTip');
        $rlt = $travelTipModel->order("update_time desc")->limit("0,1")->select();
        $strLength = mb_strlen($rlt[0]['about'],"utf8");// 获取字符个数
        $about = array();
        $item = "";
        for($index=0;$index<$strLength;$index++){
            if(mb_strlen($item,"utf8") == 13){
                $about[] = $item;
                $item = mb_substr($rlt[0]['about'], $index, 1,"utf8");
            } else {
                $item .= mb_substr($rlt[0]['about'], $index, 1,"utf8");
            }
        }
        $rlt[0]['about'] = $about;
//         if( $strLength >= 25){
//             $rlt[0]['about'] = mb_substr($rlt[0]['about'], 0, 22,"utf8")."...";
//         }
        $this->assign("travelTip", $rlt[0]);
    
        $this->display('main');
    }
    
    /**
     * 景点页面
     */
    public function featureSpot(){
        // === modle ===
        // 景点model
        $attractionModel = D('Attraction');
        // 进行分页数据查询
        $orderby['update_time']='desc';
        // 城市
        $locationCityId = $_SESSION['current_city_id'];
        if(!empty($locationCityId)){
            $where['city_id'] = $locationCityId;
        }
        // 分页
        $page = setPage($attractionModel,$where,8);
        // 景点
        $rlt = $attractionModel->where($where)->order($orderby)->limit($page->firstRow.','.$page->listRows)->select();
        $attractionList = array();
        foreach ($rlt as $attraction){
            $strLength = mb_strlen($attraction['about'],"utf8");
            if( $strLength >= 23){
                $attraction['about'] = mb_substr($attraction['about'], 0, 20,"utf8")."...";
            }
            $attractionList[] = $attraction;
        }
        $show = $page->show();// 分页显示输出
        $this->assign('page',$show);// 赋值分页输出
    
        $this->assign("attractionList", $attractionList);
        // 页脚
        $this->footer();
        $this->display('featurespot');
    }
    
    
    
    /**
     * 周边游页面
     */
    public function around(){
        // === modle ===
        // 周边游model
        $aroundModel = D('Around');
        // 进行分页数据查询
        $orderby['update_time']='desc';
        
        // 城市
        $locationCityId = $_SESSION['current_city_id'];
        if(!empty($locationCityId)){
            $where['orign'] = $locationCityId;
        }
        // 分页
        $page = setPage($aroundModel,$where,8);
        // 周边游
        $rlt = $aroundModel->where($where)->order($orderby)->limit($page->firstRow.','.$page->listRows)->select();
        $aroundList = array();
        foreach ($rlt as $around){
            $strLength = mb_strlen($around['about'],"utf8");
            if( $strLength >= 23){
                $around['about'] = mb_substr($around['about'], 0, 20,"utf8")."...";
            }
            $aroundList[] = $around;
        }
        $show = $page->show();// 分页显示输出
        $this->assign('page',$show);// 赋值分页输出
    
        $this->assign("aroundList", $aroundList);
        // 页脚
        $this->footer();
        $this->display('around');
    }
    
    /**
     * 旅游攻略页面
     */
    public function travelTips(){
        $travelTipModel = D('TravelTip');
        // 分页
        $page = setPage($travelTipModel,null,8);
        $rlt = $travelTipModel->order("update_time desc")->limit($page->firstRow.','.$page->listRows)->select();
        $travelNotesList = array();
        foreach ($rlt as $travelNotes){
            $strLength = mb_strlen($travelNotes['about'],"utf8");// 获取字符个数
            if( $strLength >= 36){
                $travelNotes['about'] = mb_substr($travelNotes['about'], 0, 33,"utf8")."...";
            }
            $travelNotesList[] = $travelNotes;
        }
        $this->assign("travel_tip_list", $travelNotesList);
        $show = $page->show();// 分页显示输出
        $this->assign('page',$show);// 赋值分页输出
        // 页脚
        $this->footer();
        $this->display('traveltips');
    }
    
    /**
     * 景点详细信息页面(商品详情)
     */
    public function featureSpotDetail(){
    
        $attractionId = I("get.id", "", "htmlspecialchars");
        // 景点model
        $attractionModel = D('Attraction');
        $where['id'] = $attractionId;
        $rlt = $attractionModel->where($where)->select();
        $attractionDetail = array();
        if(isset($rlt) && count($rlt) > 0){
            $rlt[0]['cost_explain'] = html_entity_decode($rlt[0]['cost_explain']);
            $rlt[0]['feature'] = html_entity_decode($rlt[0]['feature']);
            $rlt[0]['order_note'] = html_entity_decode($rlt[0]['order_note']);
            $rlt[0]['discount'] = html_entity_decode($rlt[0]['discount']);
            $rlt[0]['releated_product'] = html_entity_decode($rlt[0]['releated_product']);
            $attractionDetail = $rlt[0];
            $folderPath = $rlt[0]['img_folder_path'];
            if(!empty($folderPath)){
                $imgFolder = opendir("Public/Uploads/".$folderPath);
                while( ($filename = readdir($imgFolder)) !== false ){
                    if($filename != "." && $filename != "..") {
                        $imgList[] = $folderPath.'/'.$filename;
                    }
                }
                $attractionDetail['imgList'] = $imgList;
            }
        }
        $this->assign('attraction', $attractionDetail);
        
        // 获得评论
        unset($where);
        $commentModel = D('Comment');
        $where['product_id'] = $attractionId;
        $where['product_type'] = 1; // 景点
        $where['has_checked'] = 1;// 审核通过的评论
        $rlt = $commentModel->where($where)->select();
        $commentList = array();
        foreach ($rlt as $comment){
            $item = $comment;
            unset($where);
            $where['id'] = $comment['user_id'];
            $userModel = D('User');
            $user = $userModel->where($where)->select();
            if(!empty($user[0]['username']) && $user[0]['username'] != $user[0]['phone']){
                $item['comment_user_name'] = $user[0]['username'];
            } else{
                $item['comment_user_name'] = $user[0]['user_code'];
            }
            $commentList[] = $item;
        }
        $this->assign("comment_list",$commentList);
        $this->display('featurespotdetail');
    }
    
    /**
     * 周边游详情
     */
    public function aroundDetail(){
        $aroundId = I("get.id", "", "htmlspecialchars");
        // 景点model
        $aroundModel = D('Around');
        $where['id'] = $aroundId;
        $rlt = $aroundModel->where($where)->select();
        $aroundDetail = array();
        if(isset($rlt) && count($rlt) > 0){
            $rlt[0]['cost_explain'] = html_entity_decode($rlt[0]['cost_explain']);
            $rlt[0]['feature'] = html_entity_decode($rlt[0]['feature']);
            $rlt[0]['order_note'] = html_entity_decode($rlt[0]['order_note']);
            $rlt[0]['discount'] = html_entity_decode($rlt[0]['discount']);
            $rlt[0]['releated_product'] = html_entity_decode($rlt[0]['releated_product']);
            $aroundDetail = $rlt[0];
            $folderPath = $rlt[0]['img_folder_path'];
            if(!empty($folderPath)){
                $imgFolder = opendir("Public/Uploads/".$folderPath);
                while( ($filename = readdir($imgFolder)) !== false ){
                    if($filename != "." && $filename != "..") {
                        $imgList[] = $folderPath.'/'.$filename;
                    }
                }
                $aroundDetail['imgList'] = $imgList;
            }
        }
        $this->assign('around', $aroundDetail);
        
        // 获得评论
        unset($where);
        $commentModel = D('Comment');
        $where['product_id'] = $aroundId;
        $where['product_type'] = 2; // 周边游
        $where['has_checked'] = 1;// 审核通过的评论
        $rlt = $commentModel->where($where)->select();
        $commentList = array();
        foreach ($rlt as $comment){
            $item = $comment;
            unset($where);
            $where['id'] = $comment['user_id'];
            $userModel = D('User');
            $user = $userModel->where($where)->select();
            if(!empty($user[0]['username']) && $user[0]['username'] != $user[0]['phone']){
                $item['comment_user_name'] = $user[0]['username'];
            } else{
                $item['comment_user_name'] = $user[0]['user_code'];
            }
            $commentList[] = $item;
        }
        $this->assign("comment_list",$commentList);
        $this->display('arounddetail');
    }
    
    /**
     * 旅游攻略详情
     */
    public function travelTipDetail(){
        $id = I('get.id',"",'htmlspecialchars');
        if(intval($id) > 0){
            $where['id'] = $id;
            $travelTipModel = D('TravelTip');
            $rlt = $travelTipModel->where($where)->select();
            $travel_tip_detail = array();
            if(isset($rlt) && count($rlt) > 0){
                $rlt[0]['detail'] = html_entity_decode($rlt[0]['detail']);
                // 更新浏览次数
                $browse_count = $rlt[0]['browse_count'] + 1;
                $data['browse_count'] = $browse_count;
                $rs = $travelTipModel->where($where)->save($data);
                $travel_tip_detail = $rlt[0];
                $user_id = $rlt[0]['user_id'];
                unset($where);
                $where['id'] = $user_id;
                $userModel = D('User');
                $user = $userModel->where($where)->select();
                if(!empty($user[0]['real_name'])){
                    $travel_tip_detail['user_name'] = $user[0]['real_name'];
                } else if(!empty($user[0]['username'])){
                    $travel_tip_detail['user_name'] = $user[0]['username'];
                } else{
                    $travel_tip_detail['user_name'] = $user[0]['user_code'];
                }
                
            }
            $this->assign("travel_tip", $travel_tip_detail);
            
        }
        // 页脚
        $this->footer();
        $this->display('traveltipdetail');
    }
    
    /**
     * 个人中心页面
     */
    public function personCenter(){
        if(empty($_SESSION['loginUser_Index'])){
            $this->redirect("showIndex");
            exit;
        }
        $this->display('personcenter');
    }
    
    
    /**
     * 个人资料
     */
    public function personalProfile(){
        // 登录用户ID
        $user_id = $_SESSION['loginUser_Index'];
        $userModel = D('User');
        $where['id'] = $user_id;
        $rlt = $userModel->where($where)->select();
        if(empty($rlt[0]['real_name'])){
            $rlt[0]['real_name'] = "未设定";
        }
        if($rlt[0]['birthday'] == "0000-00-00"){
            $rlt[0]['birthday'] = null;
        }
        $this->assign("user",$rlt[0]);
        
        // 页脚
        $this->footer();
        $this->display('personalprofile');
    }
    
    /**
     * 我的消息
     */
    public function myMessages(){
        // 登录用户ID
        $user_id = $_SESSION['loginUser_Index'];
        $messageModel = D('Message');
        $where['accept_user_id'] = $user_id;
        // 分页
        $page = setPage($messageModel,$where,8);
        $rlt = $messageModel->where($where)->order("send_time desc")->limit($page->firstRow.','.$page->listRows)->select();
        $messageList = array();
        foreach ($rlt as $message){
            $item = $message;
            if($message['send_user_id'] == 0){
                $item['send_user_name'] = "系统消息";
                $messageList[] = $item;
                continue;
            }
            $userModel = D('User');
            unset($where);
            $where['id'] = $message['accept_user_id'];
            $user = $userModel->where($where)->select();
            if(!empty($user[0]['real_name'])){
                $item['send_user_name'] = $user[0]['real_name'];
            } else if(!empty($user[0]['username']) && $user[0]['username'] != $user[0]['phone']){
                $item['send_user_name'] = $user[0]['username'];
            } else{
                $item['send_user_name'] = $user[0]['user_code'];
            }
            $messageList[] = $item;
        }
        $show = $page->show();// 分页显示输出
        $this->assign('page',$show);// 赋值分页输出
        $this->assign("message_list", $messageList);
        
        // 页脚
        $this->footer();
        $this->display('mymessages');
    }
    
    /**
     * 我的订单
     */
    public function myOrders(){
        // 登录用户ID
        $user_id = $_SESSION['loginUser_Index'];
        $where['user_id'] = $user_id;
        $orderModel = D('Order');
        
        // 更新该用户所有订单状态
        $rlt = $orderModel->where($where)->select();
        foreach($rlt as $temp){
            // 判断订单是否过期(如果订单处于未付款状态，那么当出行日期小于等于当前日期时，订单失效
            if($temp['pay_status'] == 1 && $temp['travel_date'] <= date('Y-m-d')){
                unset($where);
                $where['id'] = $temp['id'];
                $data['pay_status'] = 4;// 订单失效
                $data['update_time'] = date('Y-m-d H:i:s');
                $rlt = $orderModel->where($where)->save($data);
            }
        }
        
        // 获取查询条件
        unset($where);
        $where['user_id'] = $user_id;
        $order_id = I('post.orderNum',"",'htmlspecialchars');
        if(!empty($order_id)){
            $where['id'] = array('like','%'.$order_id.'%');
            $this->assign("orderNum", $order_id);
        }
        $order_date_st = I('post.order_date_st',"",'htmlspecialchars');
        if(!empty($order_date_st)){
            $where['travel_date'] = array('egt',$order_date_st);
            $this->assign("order_date_st", $order_date_st);
        }
        $order_date_ed = I('post.order_date_ed',"",'htmlspecialchars');
        if(!empty($order_date_ed)){
            if(!empty($order_date_st)){
                $where['travel_date'] = array(array('egt',$order_date_st),array('elt',$order_date_ed));
            } else {
                $where['travel_date'] =  array('elt',$order_date_ed);
            }
            $this->assign("order_date_ed", $order_date_ed);
        }
        // 分页
        $page = setPageForOrder($orderModel,$where,6);
        $rlt = $orderModel->where($where)->order("update_time desc")->limit($page->firstRow.','.$page->listRows)->select();
        $orderList = array();
        foreach($rlt as $order){
            $item = $order;
            $item['total_price'] = $order['total_price_adult'] + $order['total_price_child'];
            if($order['product_type'] == 1){
                // 景点
                $attractionModel = D('Attraction');
                unset($where);
                $where['id'] = $order['product_id'];
                $product_name = $attractionModel->where($where)->getField('name');
                $item['product_name'] = $product_name;
            } else if($order['product_type'] == 2){
                // 周边游
                $atroundModel = D('Around');
                unset($where);
                $where['id'] = $order['product_id'];
                $product_name = $atroundModel->where($where)->getField('name');
                $item['product_name'] = $product_name;
            }
            
            $orderList[] = $item;
        }
        $this->assign("order_list", $orderList);
        $show = $page->show();// 分页显示输出
        $this->assign('page',$show);// 赋值分页输出
        
        // 获取待付款订单数
        unset($where);
        $where['user_id'] = $user_id;
        $where['pay_status'] = 1;
        $rlt = $orderModel->where($where)->select();
        $this->assign("un_pay_count", count($rlt));
        
        // 获取待点评订单数
        unset($where);
        $where['user_id'] = $user_id;
        $where['has_commented'] = 0;
        $where['pay_status'] = array("lt",4);
        $rlt = $orderModel->where($where)->select();
        $this->assign("un_comment_count", count($rlt));
        
        // 页脚
        $this->footer();
        $this->display('myorders');
    }
    
    /**
     * 获取订单详细
     */
    public function getOrderDetail(){
        $order_id = I("post.order_id","",'htmlspecialchars');
        if(!empty($order_id)){
            $where['id'] =  $order_id;
            $orderModel = D('Order');
            $rlt = $orderModel->where($where)->select();
            if(isset($rlt) && count($rlt) > 0){
                $order = $rlt[0];
                if($order['product_type'] == 1){
                    // 景点
                    $attractionModel = D('Attraction');
                    unset($where);
                    $where['id'] = $order['product_id'];
                    $product = $attractionModel->where($where)->select();
                    $order['product_name'] = $product[0]['name'];
                    $order['price'] = $product[0]['price'];
                } else if($order['product_type'] == 2){
                    // 周边游
                    $atroundModel = D('Around');
                    unset($where);
                    $where['id'] = $order['product_id'];
                    $product = $atroundModel->where($where)->select();
                    $order['product_name'] = $product[0]['name'];
                    $order['price'] = $product[0]['price'];
                }
                echo json_encode($order);
            } else{
                echo json_encode(array());
            }
        } else {
            echo json_encode(array());
        }
    }
    
    /**
     * 取消订单
     */
    public function removeOrder(){
        $order_id = I("post.order_id","",'htmlspecialchars');
        $user_id = $_SESSION['loginUser_Index'];
        if(!empty($order_id)){
            $where['id'] =  $order_id;
            $where['user_id'] = $user_id;
            $orderModel = D('Order');
            $data['pay_status'] = 4; //支付状态（1：待付款； 2：已付款；3：已完成；4：已失效)
            $data['update_time'] = date("Y-m-d H:i:s");
            $rlt = $orderModel->where($where)->save($data);
            if($rlt > 0){
                echo json_encode(array("status"=>200,"message"=>"您的订单已经被取消"));
            } else {
                echo json_encode(array("status"=>201,"message"=>"您的订单取消失败"));
            }
        } else {
            echo json_encode(array("status"=>400,"message"=>"订单不存在或已经被删除"));
        }
    }
    
    /**
     * 删除订单
     */
    public function deleteOrder(){
        $order_id = I("post.order_id","",'htmlspecialchars');
        $user_id = $_SESSION['loginUser_Index'];
        if(!empty($order_id)){
            $where['id'] =  $order_id;
            $where['user_id'] = $user_id;
            $orderModel = D('Order');
            $rlt = $orderModel->where($where)->delete();
            if($rlt > 0){
                echo json_encode(array("status"=>200,"message"=>"您的订单已经被删除"));
            } else {
                echo json_encode(array("status"=>201,"message"=>"您的订单删除失败"));
            }
        } else {
            echo json_encode(array("status"=>400,"message"=>"订单不存在或已经被删除"));
        }
    }
    
    /**
     * 发表评论
     */
    public function releaseComment(){
        $order_id = I("post.order_id","",'htmlspecialchars');
        // 评论内容
        $comment = I("post.comment","",'htmlspecialchars');
        $user_id = $_SESSION['loginUser_Index'];
        $where['id'] =  $order_id;
        $orderModel = D('Order');
        $rlt = $orderModel->where($where)->select();
        if(isset($rlt) && count($rlt) > 0){
            if($rlt[0]['has_commented'] == 1){
                echo json_encode(array("status"=>202,"message"=>"该订单已经被评论过"));
            }
            $data['order_id'] = $order_id;
            $data['user_id'] = $user_id;
            $data['product_id'] = $rlt[0]['product_id'];
            $data['product_type'] = $rlt[0]['product_type'];
            $data['comment'] = $comment;
            $data['comment_time'] = date("Y-m-d H:i:s");
            $data['has_checked'] = 0; // 未审核
            $commentModel = D('Comment');
            $commentModel->startTrans();
            $rs = $commentModel->data($data)->add();
            if($rs > 0){
                $orderData['pay_status'] = 3;// 支付状态（1：待付款； 2：已付款；3：已完成；4：已失效);
                $orderData['update_time'] = date("Y-m-d H:i:s");
                $orderData['has_commented'] = 1;// 已经被点评过
                $rs = $orderModel->where($where)->save($orderData);
                if($rs > 0){
                    $commentModel->commit();
                    echo json_encode(array("status"=>200,"message"=>"您的评论发表成功，请等待管理员审核。"));
                } else {
                    $commentModel -> rollback();
                    echo json_encode(array("status"=>201,"message"=>"您的评论发表失败"));
                }
            } else {
                $commentModel -> rollback();
                echo json_encode(array("status"=>203,"message"=>"您的评论发表失败"));
            }
        } else {
            echo json_encode(array("status"=>300,"message"=>"您的评论发表失败"));
        }
    }
    
    /**
     * 账户安全
     */
    public function accountSecurity(){
        // 登录用户ID
        $user_id = $_SESSION['loginUser_Index'];
        $userModel = D('User');
        $where['id'] = $user_id;
        $user = array();
        $rlt = $userModel->where($where)->select();
        if(empty($rlt[0]['email'])){
            $rlt[0]['email'] = "未设定";
        }
        $user = $rlt[0];
        // 获取登录信息
        unset($where);
        $where['user_id']= $user_id;
        $loginRecordModel = D('LoginRecord');
        $rlt = $loginRecordModel->order("login_time desc")->limit("0,1")->select();
        $user['prev_ip'] = $rlt[0]['prev_ip'];
        $user['prev_login_time'] = $rlt[0]['prev_login_time'];
        $user['prev_login_location'] = $rlt[0]['prev_login_location'];
        $this->assign("user",$user);
        
        // 获取所有密保问题
        $questionModel = D('SecurityQuestion');
        $rlt = $questionModel->select();
        $this->assign("question_list",$rlt);
        
        // 页脚
        $this->footer();
        $this->display('accountsecurity');
    }
    
    /**
     * 我的游记
     */
    public function travelNotes(){
        // 登录的用户ID
        $user_id = $_SESSION['loginUser_Index'];
        $where['user_id'] = $user_id;
        $travelTipModel = D('TravelTip');
        // 分页
        $page = setPage($travelTipModel,$where,6);
        $rlt = $travelTipModel->where($where)->order("update_time desc")->limit($page->firstRow.','.$page->listRows)->select();
        $travelNotesList = array();
        foreach ($rlt as $travelNotes){
            $strLength = mb_strlen($travelNotes['about'],"utf8");// 获取字符个数
            if( $strLength >= 25){
                $travelNotes['about'] = mb_substr($travelNotes['about'], 0, 22,"utf8")."...";
            }
            $travelNotesList[] = $travelNotes;
        }
        $this->assign("travel_notes_list", $travelNotesList);
        $show = $page->show();// 分页显示输出
        $this->assign('page',$show);// 赋值分页输出
        // 页脚
        $this->footer();
        $this->display('travelnotes');
    }
    
    /**
     * 发布游记
     */
    public function releaseNotes(){
        // 页脚
        $this->footer();
        $this->display('releasenotes');
    }
    
    /**
     * 保存发布的游记
     */
    public function saveTravelNotes(){
        // 登录的用户ID
        $user_id = $_SESSION['loginUser_Index'];
        // 游记标题
        $title = I('post.title',"","htmlspecialchars");
        // 游记内容
        $detail = I('post.detail',"","htmlspecialchars");
        // 游记摘要
        $about = I('post.about',"","htmlspecialchars");
        // 游记第一张图片的路径
        $first_img_path = I('post.first_img_path',"","htmlspecialchars");
        $data['title'] = $title;
        $data['user_id'] = $user_id;
        $data['detail'] = $detail;
        $data['about'] = $about;
        $data['first_img_path'] = $first_img_path;
        $data['release_time'] = date("Y-m-d");
        $data['update_time'] = $data['release_time']." ".date("H:i:s");
        $travelTipModel = D('TravelTip');
        $rlt = $travelTipModel->data($data)->add();
        if($rlt > 0){
            echo json_encode(array("status"=>200,"message"=>"游记发布成功"));
        } else {
            echo json_encode(array("status"=>201,"message"=>"游记发布失败"));
        }
    }
    
    /**
     * 预定生成订单
     */
    public function order(){
        $product_id = I("post.id", "", "htmlspecialchars"); // 产品ID
        $type = I("post.type", "", "htmlspecialchars"); // 1:景点；2:周边游
        $count_adult = I("post.count-adult", "", "htmlspecialchars");
        $count_child = I("post.count-child", "", "htmlspecialchars");
        $travelDate = I("post.travelDate", "", "htmlspecialchars");
        if(intval($type) == 1){
            $productModel = D('Attraction');
        } else if(intval($type) == 2){
            $productModel = D('Around');
        } else {
            echo '<script type="text/javascript>"alert("订单无效");</script>';
            exit;
        }
        $where['id'] = $product_id;
        $price = $productModel->where($where)->getField('price');
        
        $data['product_id'] = $product_id;
        $data['product_type'] = $type;
        $data['count_adult'] = intval($count_adult);
        $data['total_price_adult'] = sprintf("%.2f", intval($count_adult) * $price);// 四舍五入，并保留两位小数
        $data['count_child'] = intval($count_child);
        $data['total_price_child'] = sprintf("%.2f", intval($count_child) * ($price/2));// 四舍五入，并保留两位小数
        $data['travel_date'] = $travelDate;
        $data['user_id'] = $_SESSION['loginUser_Index'];
        $data['pay_status'] = 1;// 1：待付款； 2：已付款；3：已完成；4：已失效
        // 订单编号 时间+随机码
        $data['id'] = date("YmdHis").strval(mt_rand(1000, 9999));
        $data['order_time'] = date("Y-m-d H:i:s");
        $data['update_time'] = $data['order_time'];
        $orderModel = D('Order');
        $rlt = $orderModel->data($data)->add();
        if($rlt > 0){
            $userModel = D('user');
            unset($where);
            $where['id']= $data['user_id'];
            $user = $userModel->where($where)->select();
            if(!empty($user[0]['real_name'])){
                $data['name'] = $user[0]['real_name'];
            } else if(!empty($user[0]['username']) && $user[0]['username'] != $user[0]['phone']){
                $data['name'] = $user[0]['username'];
            } else{
                $data['name'] = $user[0]['user_code'];
            }
            $data['phone'] = $user[0]['phone'];
            $data['total_price'] = $data['total_price_adult'] + $data['total_price_child'];
            if($type == 1){
                // 景点
                $attractionModel = D('Attraction');
                unset($where);
                $where['id'] = $product_id;
                $product = $attractionModel->where($where)->select();
                $data['product_name'] = $product[0]['name'];
                $data['price'] = $product[0]['price'];
            } else if($type == 2){
                // 周边游
                $atroundModel = D('Around');
                unset($where);
                $where['id'] = $product_id;
                $product = $atroundModel->where($where)->select();
                $data['product_name'] = $product[0]['name'];
                $data['price'] = $product[0]['price'];
            }
            $this->assign("order",$data);
            // 页脚
            $this->footer();
            // 生成订单后跳转到支付页面
            $this->display('pay');
        } else {
            $this->error("生成订单失败");
            exit;
        }
    }
    
    
    /**
     * 支付
     */
    public function pay(){
        
        
        // 页脚
        $this->footer();
        $this->display('pay');
    }
    
    /**
     * 支付页面
     */
    public function payFromOrder(){
        $order_id = I("get.order_id","",'htmlspecialchars');
        if(!empty($order_id)){
            $where['id'] =  $order_id;
            $orderModel = D('Order');
            $rlt = $orderModel->where($where)->select();
            if(isset($rlt) && count($rlt) > 0){
                $order = $rlt[0];
                if($order['product_type'] == 1){
                    // 景点
                    $attractionModel = D('Attraction');
                    unset($where);
                    $where['id'] = $order['product_id'];
                    $product = $attractionModel->where($where)->select();
                    $order['product_name'] = $product[0]['name'];
                    $order['price'] = $product[0]['price'];
                } else if($order['product_type'] == 2){
                    // 周边游
                    $atroundModel = D('Around');
                    unset($where);
                    $where['id'] = $order['product_id'];
                    $product = $atroundModel->where($where)->select();
                    $order['product_name'] = $product[0]['name'];
                    $order['price'] = $product[0]['price'];
                }
                $userModel = D('user');
                unset($where);
                $where['id']= $order['user_id'];
                $user = $userModel->where($where)->select();
                if(!empty($user[0]['real_name'])){
                    $order['name'] = $user[0]['real_name'];
                } else if(!empty($user[0]['username']) && $user[0]['username'] != $user[0]['phone']){
                    $order['name'] = $user[0]['username'];
                } else{
                    $order['name'] = $user[0]['user_code'];
                }
                $order['phone'] = $user[0]['phone'];
                $order['total_price'] = $order['total_price_adult'] + $order['total_price_child'];
                $this->assign("order",$order);
                // 页脚
                $this->footer();
                $this->display('pay');
            } else{
                 $this->error("获取订单失败");
            }
        } else {
            $this->error("获取订单失败");
        }
    }
    
    /**
     * 验证码
     */
    public function verify(){
        $config =    array(
            'fontSize'    =>    50, // 验证码字体大小  
            'length'      =>    4, // 验证码位数   
            'useNoise'    =>    false, // 关闭验证码杂点
            );
        $verify = new Verify($config);
        $verify->entry("yida");
    }
    
    /**
     * 验证码检测
     * @param string $id
     * @return boolean
     */
    public function checkVerify(){
        $code = I('post.code', '', 'htmlspecialchars');
        $verify = new \Think\Verify();  
        if($verify->check($code, "yida")){
            echo "true";
        } else {
            echo "false";
        }
    }
    
    /**
     * 保存个人信息
     */
    public function savePersonInfo(){
        $userModel = D('User');
        // 手机号
        $phone = I('post.phone', '', 'htmlspecialchars');
        // 邮箱
        $email = I('post.email', '', 'htmlspecialchars');
        // 会员编号
        $user_code = I('post.user_code', '', 'htmlspecialchars');
        // 昵称
        $username = I('post.username', '', 'htmlspecialchars');
        // 真实姓名
        $real_name = I('post.real_name', '', 'htmlspecialchars');
        // 性别
        $sex = I('post.sex', '', 'htmlspecialchars');
        // 出生日期
        $birthday = I('post.birthday', '', 'htmlspecialchars');
        // 证件类型
        $credentials_type = I('post.credentials_type', '', 'htmlspecialchars');
        // 证件号
        $credentials = I('post.credentials', '', 'htmlspecialchars');
        // 固定电话区号
        $area_code = I('post.area_code', '', 'htmlspecialchars');
        // 固定电话
        $telephone = I('post.telephone', '', 'htmlspecialchars');
        // 地址
        $address = I('post.address', '', 'htmlspecialchars');
        // 邮编
        $postcode = I('post.postcode', '', 'htmlspecialchars');
        if(!empty($phone)){
            $data['phone'] = $phone;
        }
        if(!empty($user_code)){
            $data['user_code'] = $user_code;
        }
        if(!empty($username)){
            $data['username'] = $username;
        }
        if(!empty($real_name)){
            $data['real_name'] = $real_name;
        }
        $data['email'] = $email;
        $data['sex'] = $sex;
        $data['birthday'] = $birthday;
        $data['credentials_type'] = $credentials_type;
        $data['credentials'] = $credentials;
        $data['area_code'] = $area_code;
        $data['telephone'] = $telephone;
        $data['address'] = $address;
        $data['postcode'] = $postcode;
        $where['id'] = $_SESSION['loginUser_Index'];
        $rlt = $userModel->where($where)->save($data);
        if($rlt != 0 && $rlt == false){
            $this->error('个人资料保存失败！');
        } else {
            $this->success('个人资料保存成功', 'personalProFile');
        }
    }
    
    /**
     * check原密码
     */
    public function checkOldPwd(){
        $userModel = D('User');
        $password = I('post.oldpassword', '', 'htmlspecialchars');
        $where['id'] = $_SESSION['loginUser_Index'];
        $rlt = $userModel->where($where)->select();
        if(isset($rlt)){
            if(md5($password) == $rlt[0]['password']){
                echo json_encode(array("status"=>200,"message"=>"密码输入正确！"));
            } else {
                echo json_encode(array("status"=>201,"message"=>"密码输入错误！"));
            }
        }
    }
    
    /**
     * 修改密码
     */
    public function alterPwd(){
        $userModel = D('User');
        // 密码
        $password = I('post.password', '', 'htmlspecialchars');
    
        $data['password'] = md5($password);
        $where['id'] = $_SESSION['loginUser_Index'];
        $rlt = $userModel->where($where)->save($data);
        if($rlt != 0 && $rlt == false){
            echo json_encode(array("status"=>201,"message"=>"密码修改失败！"));
        } else {
            echo json_encode(array("status"=>200,"message"=>"密码修改成功！"));
        }
    }
    
    /**
     * 重置密码
     */
    public function resetPwd(){
        $userModel = D('User');
        // 密码
        $password = I('post.password', '', 'htmlspecialchars');
        // 修改密码依据
        $key = I('post.phone', '', 'htmlspecialchars');
        $where['phone'] = $key;
        $data['password'] = md5($password);
        $rlt = $userModel->where($where)->save($data);
        if($rlt != 0 && $rlt == false){
            echo json_encode(array("status"=>201,"message"=>"重置密码失败！"));
        } else {
            echo json_encode(array("status"=>200,"message"=>"重置密码成功！"));
        }
    }
    
    /**
     * 设定密保问题
     */
    public function setSecurity(){
        $user_id = $_SESSION['loginUser_Index'];
        
        $question_1 = I('post.question_1', '', 'htmlspecialchars');
        $question_2 = I('post.question_2', '', 'htmlspecialchars');
        $question_3 = I('post.question_3', '', 'htmlspecialchars');
        $answer_1 = I('post.answer_1', '', 'htmlspecialchars');
        $answer_2 = I('post.answer_2', '', 'htmlspecialchars');
        $answer_3 = I('post.answer_3', '', 'htmlspecialchars');
        
        $data['user_id'] = $user_id;
        $data['question_1_id'] = $question_1;
        $data['question_2_id'] = $question_2;
        $data['question_3_id'] = $question_3;
        $data['question_1_answer'] = $answer_1;
        $data['question_2_answer'] = $answer_2;
        $data['question_3_answer'] = $answer_3;
        
        $where['user_id'] = $user_id;
        $answerModel = D('SecurityAnswer');
        $id = $answerModel->where($where)->getField('id');
        if(isset($id) && $id > 0){
            // 更新密保问题
            $where['id'] = $id;
            $data['update_time'] = date('Y-m-d H:i:s');
            $rlt = $answerModel->where($where)->save($data);
        } else {
            // 新设定密保问题
            $data['create_time'] = date('Y-m-d H:i:s');
            $data['update_time'] = $data['create_time'];
            $rlt = $answerModel->data($data)->add();
        }
        if($rlt > 0){
            echo json_encode(array("status"=>200,"message"=>"密保问题设置成功！"));
        } else {
            echo json_encode(array("status"=>201,"message"=>"密保问题设置失败！"));
        }
    }
    
    /**
     * 绑定支付宝
     */
    public function saveAlipay(){
        $userModel = D('User');
        // 支付宝
        $alipay = I('post.alipay', '', 'htmlspecialchars');
    
        $data['alipay'] = $alipay;
        $where['id'] = $_SESSION['loginUser_Index'];
        $rlt = $userModel->where($where)->save($data);
        if($rlt != 0 && $rlt == false){
            echo json_encode(array("status"=>201,"message"=>"绑定支付宝失败！"));
        } else {
            echo json_encode(array("status"=>200,"message"=>"绑定支付宝成功！"));
        }
    }
    
    /**
     * 绑定手机号码
     */
    public function savePhone(){
        $userModel = D('User');
        // 手机号码
        $phone = I('post.phone', '', 'htmlspecialchars');
        $data['phone'] = $phone;
        if($this->checkHasExisted($data) == false){
            $where['id'] = $_SESSION['loginUser_Index'];
            $rlt = $userModel->where($where)->select();
            if($rlt[0]['username'] == $rlt[0]['phone']){
                $data['username'] = $phone;
            }
            $rlt = $userModel->where($where)->save($data);
            if($rlt != 0 && $rlt == false){
                echo json_encode(array("status"=>201,"message"=>"手机号修改失败"));
            } else {
                echo json_encode(array("status"=>200,"message"=>"手机号修改成功"));
            }
        } else {
            echo json_encode(array("status"=>201,"message"=>"手机号已存在"));            
        }
    }
    
    /**
     * 修改会员编号
     */
    public function saveUserCode(){
        $userModel = D('User');
        // 手机号码
        $user_code = I('post.user_code', '', 'htmlspecialchars');
        $data['user_code'] = $user_code;
        if($this->checkHasExisted($data) == false){
            $where['id'] = $_SESSION['loginUser_Index'];
            $rlt = $userModel->where($where)->save($data);
            if($rlt != 0 && $rlt == false){
                echo json_encode(array("status"=>201,"message"=>"会员名修改失败"));
            } else {
                echo json_encode(array("status"=>200,"message"=>"会员名修改成功"));
            }
        } else {
            echo json_encode(array("status"=>201,"message"=>"会员名已存在"));
        }
    }
    
    /**
     * 修改昵称
     */
    public function saveUsername(){
        $userModel = D('User');
        // 手机号码
        $username = I('post.username', '', 'htmlspecialchars');
        $data['username'] = $username;
        if($this->checkHasExisted($data) == false){
            $where['id'] = $_SESSION['loginUser_Index'];
            $rlt = $userModel->where($where)->save($data);
            if($rlt != 0 && $rlt == false){
                echo json_encode(array("status"=>201,"message"=>"昵称修改失败"));
            } else {
                echo json_encode(array("status"=>200,"message"=>"昵称修改成功"));
            }
        } else {
            echo json_encode(array("status"=>201,"message"=>"昵称已存在"));
        }
    }
    
    /**
     * 修改真实姓名
     */
    public function saveRealName(){
        $userModel = D('User');
        // 手机号码
        $real_name = I('post.real_name', '', 'htmlspecialchars');
        $data['real_name'] = $real_name;
        if($this->checkHasExisted($data) == false){
            $where['id'] = $_SESSION['loginUser_Index'];
            $rlt = $userModel->where($where)->save($data);
            if($rlt != 0 && $rlt == false){
                echo json_encode(array("status"=>201,"message"=>"真实姓名修改失败"));
            } else {
                echo json_encode(array("status"=>200,"message"=>"真实姓名修改成功"));
            }
        } else {
            echo json_encode(array("status"=>201,"message"=>"真实姓名已存在"));
        }
    }
    
    /**
     * 设置邮箱
     */
    public function setEmail(){
        $userModel = D('User');
        // 手机号码
        $email = I('post.email', '', 'htmlspecialchars');
        $data['email'] = $email;
        if($this->checkHasExisted($data) == false){
            $where['id'] = $_SESSION['loginUser_Index'];
            $rlt = $userModel->where($where)->save($data);
            if($rlt != 0 && $rlt == false){
                echo json_encode(array("status"=>201,"message"=>"邮箱设置失败"));
            } else {
                echo json_encode(array("status"=>200,"message"=>"邮箱设置成功"));
            }
        } else {
            echo json_encode(array("status"=>201,"message"=>"该邮箱已经被使用"));
        }
        
    }
    
    /**
     * 检查指定信息是否已经存在。以json返回.status=200:已存在;status=500:不存在
     */
    public function checkHasExistedRtnJson(){
        // 手机号码
        $phone = I('post.phone', '', 'htmlspecialchars');
        // 会员名(会员编号)
        $user_code = I('post.user_code', '', 'htmlspecialchars');
        // 昵称
        $username = I('post.username', '', 'htmlspecialchars');
        // 邮箱
        $email = I('post.email', '', 'htmlspecialchars');
        
        if(!empty($phone)){
            $params['phone'] = $phone;
            $message = "您输入的手机号";
        }
        
        if(!empty($user_code)){
            $params['user_code'] = $user_code;
            $message = "您输入的会员名";
        }
        
        if(!empty($username)){
            $params['username'] = $username;
            $message = "您输入的昵称";
        }
        
        if(!empty($email)){
            $params['email'] = $email;
            $message = "您输入的邮箱";
        }
        
        if($this->checkHasExisted($params) == true){
            echo json_encode(array("status"=>200,"message"=>$message."已经存在"));
        } else {
            echo json_encode(array("status"=>500,"message"=>"不存在"));
        }
    }
    
    /**
     * 检查手机号,会员名,昵称等是否已经存在
     * @param $params key:DB中各个字段名。如：`phone`,`user_code`,`username`.value:DB中各个字段所对应的值。如13511111111，00000001，我哦我我
     * @return boolean
     */
    private function checkHasExisted($params = array()){
        $userModel = D('User');
        foreach ($params as $key=>$value){
            $where[$key] = $value;
        }
        $rlt = $userModel->where($where)->getField("id");
        if($rlt > 0){
            return true; // 已存在
        } else {
            return false;  // 不存在
        }
    }
    
    /**
     * 订单详情
     */
    public function orderDetail(){
        $orderModel = D('Order');
        $id = I('get.id', "", "htmlspecialchars");
        $where['id']= $id;
        $rlt = $orderModel->where($where)->select();
        if(isset($rlt)){
            $this->assign('order', $rlt[0]);
            $ticketWhere['id'] = $rlt[0]['ticket_id'];
            $ticketModel = D('Ticket');
            $ticket = $ticketModel->where($ticketWhere)->select();
            if(isset($ticket)){
                $this->assign('ticket', $ticket[0]);
            }
        }
        $this->display('orderdetail');
    }
    
    /**
     * 发送短信验证码
     */
    public function sendSmsVerify(){
        $phone = I('post.phone', "", 'htmlspecialchars');
        $verifyCode = $this->randomkeys(6);
        if(!empty($phone)){
          $info = SendMsg($phone, "验证码".$verifyCode);
          cookie("sms_code_".$phone,$verifyCode,array('expire'=>3600 * 2 ,'prefix'=>'yida_'));
          echo json_encode(array("status"=> 200,"message"=>"动态密码发送成功"));
        }
    }
    
    /**
     * 发送邮件验证码
     */
    public function sendEmailVerify(){
        $emailAddress = I('post.email', "", 'htmlspecialchars');
        $verifyCode = $this->randomkeys(6);
        if(!empty($emailAddress)){
            $title = "义达生态旅游会员重置密码验证";
            $content = '亲爱的会员： 您好！<br>您正在重置密码，请在验证码输入框中输入：<label style="color:red;">'.$verifyCode.'</label>,以完成操作。';
            $info = SendMail($emailAddress, $title,$content);
            if($info != false){
                cookie("sms_code_".$emailAddress,$verifyCode,array('expire'=>3600 * 2 ,'prefix'=>'yida_'));
                echo json_encode(array("status"=> 200,"message"=>"验证码发送成功"));
            } else {
                echo json_encode(array("status"=> 201,"message"=>"验证码发送失败"));
            }
        }
    }
    
    /**
     * 校验短信验证码
     */
    public function checkSmsVerify(){
        $phone = I('post.phone', "", 'htmlspecialchars');
        $smsVerifyCode = I('post.smsVerifyCode', "", 'htmlspecialchars');
        $sendedSmsCode = cookie('yida_sms_code_'.$phone);
        if(empty($sendedSmsCode)){
            echo json_encode(array("status"=>400,"message"=>"动态密码已失效，请重新获取！"));
        } else if($sendedSmsCode == $smsVerifyCode){
            cookie("sms_code_".$phone,null,array('expire'=>3600 * 2 ,'prefix'=>'yida_'));
            echo json_encode(array("status"=>200,"message"=>"密码正确！"));
        } else{
            echo json_encode(array("status"=>201,"message"=>"输入的动态密码不正确！"));
        }
    }
    
    /**
     * 生成随机数
     * @param  $length 随机数长度
     * @return string
     */
    private function randomkeys($length){
        $output='';
        for($a=0;$a<$length;$a++){
            $output.=mt_rand(0,9);//生成php随机数
        }
        return $output;
    }
    
    /**
     * 页脚的推荐景点和推荐周边游
     */
    private function footer(){
        // 城市
        $locationCityId = $_SESSION['current_city_id'];
        if(!empty($locationCityId)){
            $where['city_id'] = $locationCityId;
        }
        
        // === 推荐景点 ===
        // 景点model
        $attractionModel = D('Attraction');
        // 进行分页数据查询
        $orderby['update_time']='desc';
        // 景点
        $rlt = $attractionModel->where($where)->order($orderby)->limit("0".','."6")->select();
        $attractionList = array();
        foreach ($rlt as $attraction){
            $strLength = mb_strlen($attraction['about'],"utf8");
            if( $strLength >= 25){
                $attraction['about'] = mb_substr($attraction['about'], 0, 22,"utf8")."...";
            }
            $attractionList[] = $attraction;
        }
        $this->assign("recommendAttrList", $attractionList);
    
        // === 推荐周边游 ===
        // 景点model
        $aroundModel = D('Around');
        // 进行分页数据查询
        $orderby['update_time']='desc';
        if(!empty($locationCityId)){
            $where_around['orign'] = $locationCityId;
        }
        // 周边游
        $rlt = $aroundModel->where($where_around)->order($orderby)->limit("0".','."6")->select();
        $aroundList = array();
        foreach ($rlt as $around){
            $strLength = mb_strlen($around['about'],"utf8");
            if($strLength >= 25){
                $around['about'] = mb_substr($around['about'], 0, 22,"utf8")."...";
            }
            $aroundList[] = $around;
        }
        $this->assign("recommendAroundList", $aroundList);
    }
    
    /**
     * 显示协议内容
     */
    public function showProtocol(){
        $protocolId = I('get.id',"",'htmlspecialchars');
        $protocolModel = D('Protocol'); 
        if(intval($protocolId) > 0){
            $where['id'] = $protocolId;
            $rlt = $protocolModel->where($where)->select();
            $rlt[0]['protocol'] = html_entity_decode($rlt[0]['protocol']);
            $this->assign("protocol",$rlt[0]);
            $this->display("showprotocol");
        } else {
            $this->error("没有获取到相关协议");
        }
    }
}